package com.atzly.community.event;

import com.alibaba.fastjson.JSONObject;
import com.atzly.community.constant.CommentConstant;
import com.atzly.community.entity.DiscussPost;
import com.atzly.community.entity.Event;
import com.atzly.community.entity.Message;
import com.atzly.community.service.DiscussPostService;
import com.atzly.community.service.ElastaticSearchService;
import com.atzly.community.service.MessageService;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 事件消费者
 *
 * @author zlysimida
 * @date 2021/9/1 - 9:47
 */
@Component
@Slf4j
public class EvenConsumer implements CommentConstant {

    @Autowired
    private MessageService messageService;

    @Autowired
    private ElastaticSearchService esSearch;

    @Autowired
    private DiscussPostService discussPostService;

    @Value("${wk.image.command}")
    private String command;

    @Value("${wk.image.param}")
    private String param;

    @Value("${wk.image.storage}")
    private String storgeLocation;

    @KafkaListener(topics = {TOPIC_COMMENT_KEY, TOPIC_LIKE_KEY, TOPIC_FOLLOW_KEY})
    public void handleMessage(ConsumerRecord record) {

        if (record == null || record.value() == null) {
            log.error("接收到的事件对象为空!");
            return;
        }

        Event event = JSONObject.parseObject(record.value().toString(), Event.class);
        if (event == null) {
            log.error("事件不能为空");
            return;
        }
        // 发送通知
        Message message = new Message();
        message.setFromId(SYSTEM_USER_ID);
        message.setToId(event.getEntityUserId());
        message.setConversationId(event.getTopic());
        message.setCreateTime(new Date());

        Map<String, Object> content = new HashMap<>();
        content.put("userId", event.getUserId());
        content.put("entityType", event.getEntityType());
        content.put("entityId", event.getEntityId());

        Map<String, Object> datas = event.getData();
        if (!datas.isEmpty()) {
            for (Map.Entry<String, Object> entry : datas.entrySet()) {
                content.put(entry.getKey(), entry.getValue());
            }
        }
        message.setContent(JSONObject.toJSONString(content));
        messageService.insertMessage(message);
    }

    // 消费帖子事件
    @KafkaListener(topics = {TOPIC_PUBLISH})
    public void publishPost(ConsumerRecord record) {
        if (record == null || record.value() == null) {
            log.error("接收到的事件对象为空!");
            return;
        }

        Event event = JSONObject.parseObject(record.value().toString(), Event.class);
        if (event == null) {
            log.error("事件不能为空");
            return;
        }

        DiscussPost post = discussPostService.selectDiscussDetails(event.getEntityId());
        esSearch.addEntityToEs(post);
    }

    // 消费帖子删除事件
    @KafkaListener(topics = {TOPIC_DELETE})
    public void deletePost(ConsumerRecord record) {
        if (record == null || record.value() == null) {
            log.error("接收到的事件对象为空!");
            return;
        }

        Event event = JSONObject.parseObject(record.value().toString(), Event.class);
        if (event == null) {
            log.error("事件不能为空");
            return;
        }
        esSearch.removeEntityFromEs(event.getEntityId());
    }

    // 消费长图任务
    @KafkaListener(topics = {TOPIC_SHARE_IMAGE})
    public void growImage(ConsumerRecord record) {
        if (record == null || record.value() == null) {
            log.error("接收到的事件对象为空!");
            return;
        }

        Event event = JSONObject.parseObject(record.value().toString(), Event.class);
        if (event == null) {
            log.error("事件不能为空");
            return;
        }

        // 生成长图
        String htmlUrl = (String) event.getData().get("htmlUrl");
        String filename = (String) event.getData().get("filename");
        String suffix = (String) event.getData().get("suffix");

        // 保存到本地
        // 参数格式
        String cmd = command + param + htmlUrl + " " + storgeLocation + "/" + filename + suffix;
        try {
            Runtime.getRuntime().exec(cmd);
            log.info("生成长图成功: " + cmd);
        } catch (IOException e) {
            log.error("生成长图失败:  + e.getMessage()");
        }

    }
}
